<template>
  <div class="keys-container" v-if="isLargeScreen()">
    <div class="keyChar" v-show="typedKeys.length > 0">
      <span v-for="(key, index) in typedKeys" :key="key.id" :style="getKeyStyle(index)">
        {{ key.char }}
      </span>
    </div>
    <div v-for="k in realKeys" :key="k" class="block">
      <el-image
        :style="k.hit === true ? 'transform: scale(1.1);filter: sepia(1);' : ''"
        class="key-image"
        :src="k.url"
        fit="contain"
      />
      <span class="description">{{ k.desc }}</span>
    </div>
  </div>
</template>
<script>
import { KeyboardAudioCls } from '../../utils/keyboardAudio'
export default {
  name: 'KeyQuick',
  components: { KeyboardAudioCls },
  props: {
    keys: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      disappearDelay: 2000,
      timer: null,
      typedKeys: [], // 替换原来的单个字符跟踪变量
      KeyboardAudio: new KeyboardAudioCls(),
      realKeys: [],
      keyBoardKeys: [
        {
          name: 'left',
          desc: '上一句',
          keyValue: 'ArrowLeft',
          url: '/assets/keys/left.png'
        },
        {
          name: 'right',
          desc: '下一句',
          keyValue: 'ArrowRight',
          url: '/assets/keys/right.png'
        },
        {
          name: 'enter',
          desc: '播放',
          keyValue: 'Enter',
          url: '/assets/keys/enter.png'
        },
        {
          name: 'ctrl',
          desc: '提示',
          keyValue: 'Control',
          url: '/assets/keys/control.png'
        },
        {
          name: '[',
          desc: '重置',
          keyValue: '[',
          url: '/assets/keys/left-square-bracket.png'
        }
      ]
    }
  },
  mounted() {
    for (let i = 0; i < this.keys.length; i++) {
      const key = this.keys[i]
      const filterKey = this.keyBoardKeys.find((k) => k.name === key)
      this.realKeys.push(filterKey)
    }
    // 注册document的键盘按下事件
    document.addEventListener('keydown', (event) => {
      if (event.key.length > 1) {
        return
      }

      // 添加新的键入字符到数组开头
      this.typedKeys.unshift({
        id: Date.now() + Math.random(), // 唯一标识符
        char: event.key,
        timestamp: Date.now()
      })

      // 清理超过1秒的字符
      this.cleanupOldKeys()

      // 启动定期清理检查
      if (!this.cleanupInterval) {
        this.cleanupInterval = setInterval(() => {
          this.cleanupOldKeys()
        }, 100)
      }
    })

    for (let i = 0; i < this.keyBoardKeys.length; i++) {
      const key = this.keyBoardKeys[i]
      this.KeyboardAudio.register(key.keyValue, () => {
        const x = (theKey) => {
          if (theKey.keyValue === key.keyValue) {
            theKey.hit = true
            setTimeout(() => {
              theKey.hit = false
            }, 200)
          }
        }
        return x(key)
      })
    }
  },
  beforeUnmount() {
    // 清理定时器
    if (this.cleanupInterval) {
      clearInterval(this.cleanupInterval)
    }
  },
  methods: {
    isLargeScreen() {
      return window.innerWidth > 768
    },
    cleanupOldKeys() {
      const now = Date.now()
      // 移除超过1秒的字符
      this.typedKeys = this.typedKeys.filter((key) => now - key.timestamp < this.disappearDelay)

      // 如果没有字符了，清除定时器
      if (this.typedKeys.length === 0 && this.cleanupInterval) {
        clearInterval(this.cleanupInterval)
        this.cleanupInterval = null
      }
    },
    getKeyStyle(index) {
      const now = Date.now()
      const key = this.typedKeys[index]
      const age = now - key.timestamp // 毫秒

      // 计算透明度 (1秒内的字符从1到0.1)
      const opacity = Math.max(0.1, this.disappearDelay / 1000 - age / this.disappearDelay)

      // 计算字体大小 (最新的字符最大，最老的字符最小)
      const fontSize = Math.max(0.5, 4 - (age / this.disappearDelay) * 3) // 从4rem到1rem

      // 计算位置偏移，使字符向左移动
      const position = index * 25 // 每个字符相对于前一个字符的水平偏移量
      // 随机一种亮色
      const color = `hsl(${Math.random() * 360}, 100%, 50%)`
      return {
        'z-index': Math.floor(this.disappearDelay - age),
        opacity: opacity,
        color: color,
        fontSize: fontSize + 'rem',
        transform: `translateX(${-position}px)`,
        transition: 'all 0.1s linear'
      }
    }
  }
}
</script>
<style scoped lang="scss">
.keys-container {
  display: flex;
  flex-wrap: wrap;
  justify-content: center;
  align-items: center;
  margin: 0 auto;
  max-width: 1000px;
  .key-image {
    width: 60px;
    height: 60px;
  }
  .key-image:hover {
    cursor: pointer;
    transform: scale(1.1);
  }
  .keyChar {
    position: absolute;
    top: 200px;
    right: 50%;
    display: flex;
    justify-content: center;
    align-items: center;
    font-weight: bold;
    font-family: 'DynaPuff';
    span {
      line-height: 4rem;
      height: 4rem;
      display: block;
      padding: 4px 8px;
      position: absolute;
      animation: opacityToZero 2s linear forwards;
    }
    @keyframes opacityToZero {
      0% {
        opacity: 1;
      }
      100% {
        opacity: 0;
      }
    }
  }
}

.block {
  display: flex;
  flex-direction: column;
  align-items: center;
  margin: 10px;
}

.description {
  font-size: 12px;
}
</style>